package com.wt.springsamples.initializer;

import com.wt.springsamples.filter.LoginFilter;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.support.XmlWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;

import javax.servlet.DispatcherType;
import javax.servlet.FilterRegistration;
import javax.servlet.ServletContext;
import javax.servlet.ServletRegistration;
import java.util.EnumSet;

/**
 * 1、servlet3.0规范规定META-INF/services目录下存在javax.servlet.ServletContainerInitializer文件，
 *  内容为org.springframework.web.SpringServletContainerInitializer
 *  2、SpringServletContainerInitializer实现了Servlet3.0接口ServletContainerInitializer
 *  3、SpringServletContainerInitializer通过注解@HandlesTypes(WebApplicationInitializer.class)指明处理所有WebApplicationInitializer的实现类
 *  4、WebApplicationInitializer为spring mvc提供的接口，目前只对war启动的项目有效，Spring Boot方式启动无效（需要实现ServletContextInitializer才起作用）
 */
public class MyWebApplicationInitializer implements WebApplicationInitializer {

    @Override
    public void onStartup(ServletContext container) {
        XmlWebApplicationContext appContext = new XmlWebApplicationContext();
        appContext.setConfigLocation("/WEB-INF/spring/dispatcher-config.xml");

        ServletRegistration.Dynamic registration = container.addServlet("dispatcher", new DispatcherServlet(appContext));
        registration.setLoadOnStartup(1);
        registration.addMapping("/");

        FilterRegistration.Dynamic  filterRegistration = container.addFilter("loginFilter",new LoginFilter());
        filterRegistration.addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST),true,"/*");
    }
}